import { createApp } from 'vue'
import Loading from './base/loading'
import NoResult from './base/no-result/no-result.vue'
const div = document.createElement('div')
div.setAttribute('class', 'loading')
document.body.appendChild(div)
export default {
  install (app) {
    loadingdir(app)
    noResult(app)
  }
}
function loadingdir (app) {
  app.directive('loading', {
    mounted (el, binding) {
      if (binding.value) {
        const loadingapp = createApp(Loading)
        const instance = loadingapp.mount(div)
        el[Loading.name] = {}
        el[Loading.name].instance = instance.$el
        append(el, instance.$el)
        instance.setTitle('正在加载')
      }
    },
    updated (el, binding) {
      // 此处重点注意需要加一个instance.$el.parentElement !== el的判断
      // 因为当组件绑定了v-loading，这里的updated将会一直存在，可能会出先removeChild的的时候元素不存在
      if (binding.oldValue !== binding.value) {
        const instance = el[Loading.name].instance
        if (binding.value) {
          append(el, instance)
        }
        if (!binding.value && instance.parentElement === el) {
          el.removeChild(instance)
        }
      }
    }
  })
}

function noResult (app) {
  app.directive('noResult', {
    mounted (el, binding) {
      if (binding.value) {
        const noresultapp = createApp(NoResult)
        const instance = noresultapp.mount(div)
        instance[NoResult.name] = {}
        instance[NoResult.name].instance = instance
        el.appendChild(instance.$el)
        instance.setTitle('没有数据')
      }
    },
    updated (el, binding) {
      // 此处重点注意需要加一个instance.$el.parentElement !== el的判断
      // 因为当组件绑定了v-loading，这里的updated将会一直存在，可能会出先removeChild的的时候元素不存在
      if (!el[NoResult.name]) return
      const instance = el[NoResult.name].instance
      if (binding.oldValue !== binding.value) {
        // debugger
        if (binding.value && instance.$el.parentElement !== el) {
          el.appendChild(instance.$el)
        }
        if (!binding.value && instance.$el.parentElement === el) {
          el.removeChild(instance.$el)
        }
      }
    }
  })
}

// 添加元素
const append = (el, instance) => {
  el.appendChild(instance)

  // debugger
  // console.log(window.getComputedStyle(el))
  // const style = window.getComputedStyle(el)
  // if (['absolute', 'fixed', 'relative'].indexOf(style.position) === -1) {
  //   el.setAttribute('class', 'absoluteclass')
  // }
  // el.appendChild(instance)
}
